package com.atguigu.springboot.controller;

import com.atguigu.springboot.exception.UserNotExistsException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : leimingchao
 * @date Date : 2021年10月16日 20:17
 */
@ControllerAdvice
public class MyExceptionHandler {

    /**
     * 1.浏览器和客户端都是json数据
     * @param exception
     * @return
     */
    // @ResponseBody
    // @ExceptionHandler(value = UserNotExistsException.class)
    // public Map<String,Object> handlerException(Exception exception) {
    //
    //     Map<String,Object> map = new HashMap<>();
    //     map.put("code","user.notexist");
    //     map.put("message", exception.getMessage());
    //     return map;
    // }

    @ExceptionHandler(value = UserNotExistsException.class)
    public String handlerException(Exception exception, HttpServletRequest request) {

        Map<String,Object> map = new HashMap<>();
        //传入我们自己的错误状态码 4xx 5xx
        /**
         * Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
         */
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("code","user.notexist");
        map.put("message", "用户出错了");
        request.setAttribute("ext",map);
        //转发到error
        return "forward:/error";
    }
}
